package com.huatai.exchange.deal;

import com.alibaba.fastjson.JSON;
import com.faneui.common.exception.BusinessException;
import com.faneui.common.utils.CloseUtils;
import com.faneui.common.utils.DateFormatUtils;
import com.faneui.common.utils.ZipUtil;
import com.faneui.integration.smb.SmbFileUtils;
import com.huatai.exchange.dal.model.ExcDataFileInfo;
import com.huatai.exchange.dal.model.ExcExchangeDateFile;
import com.huatai.exchange.facade.Contents;
import com.huatai.exchange.facade.FileSourceContents;
import com.huatai.exchange.utils.FileDealUtils;
import de.schlichtherle.util.zip.ZipOutputStream;
import jcifs.smb.NtlmPasswordAuthentication;
import jcifs.smb.SmbFile;
import org.springframework.stereotype.Service;

import java.io.File;
import java.io.FileOutputStream;
import java.util.Date;
import java.util.HashMap;
import java.util.Map;
import java.util.UUID;
import java.util.regex.Pattern;

@Service("fileCreateSmbDealService")
public class FileCreateSmbDealServiceImpl extends AbstractFileCreateDealServiceImpl implements FileCreateDealService{

    @Override
    public void downloadCreateFile(StringBuffer fileNames, StringBuffer filePaths, ExcExchangeDateFile exchangeDateFile, ExcDataFileInfo dataFileInfo, Map<String, Object> resvMap) throws BusinessException {
        Map<String, Object> excDataFileMap = JSON.parseObject(exchangeDateFile.getProperties(), HashMap.class);
        Map<String, Object> valueMap = JSON.parseObject(dataFileInfo.getValue(), HashMap.class);
        String fileName = FileDealUtils.formatStr(dataFileInfo.getFileName(), excDataFileMap, resvMap);
        String smbFileUrl = FileDealUtils.formatStr((String) valueMap.get(FileSourceContents.SMB_URL), excDataFileMap, resvMap);
        NtlmPasswordAuthentication auth = SmbFileUtils.createAuthHdisk();
        if (resvMap.get(FileSourceContents.SMB_USER_NAME) != null) {
            auth = SmbFileUtils.createAuth(smbFileUrl, (String) resvMap.get(FileSourceContents.SMB_USER_NAME),
                    (String) resvMap.get(FileSourceContents.SMB_PASSWORD));
        }

        String tmpFilePath = tmpFile + UUID.randomUUID().toString();
        File f = new File(tmpFilePath);
        String fileMoreFlag = (String) valueMap.get(FileSourceContents.FILE_MORE_FLAG);
        if (Contents.boolean_true.equals(fileMoreFlag)) {
            String fileDir = FileDealUtils.formatStr(smbFileUrl.substring(0, smbFileUrl.lastIndexOf("/") + 1), excDataFileMap, resvMap);
            String regex = FileDealUtils.formatStr(smbFileUrl.substring(smbFileUrl.lastIndexOf("/") + 1), excDataFileMap, resvMap);
            Pattern pattern = Pattern.compile(regex);
            logger.info("fileDir：" + fileDir);
            logger.info("regex：" + regex);
            ZipOutputStream zos = null;
            FileOutputStream fos = null;
            File tmpFile = new File(tmpFilePath+UUID.randomUUID().toString()) ;
            try {
                SmbFile dir = new SmbFile(fileDir, auth);
                SmbFile[] smbFiles = dir.listFiles();
                fos = new FileOutputStream(f);
                zos = new ZipOutputStream(fos, ZipUtil.charset);
                for (SmbFile smbFile : smbFiles) {
                    if (pattern.matcher(smbFile.getName()).find()) {
                        logger.info("fn-----:" + smbFile.getName());
                        logger.info("-----------------");
                        FileDealUtils.zip(zos,tmpFile, smbFile);
                    }
                }
                logger.info("--------文件push成功---------");
            } catch (Exception ex) {
                BusinessException.throwBusinessException(ex);
            } finally {
                CloseUtils.safeClose(zos, fos);
                tmpFile.deleteOnExit();
            }
            logger.info("--------开始上传---------");
            String filePath = fileOperateService.uploadFile(f);
            logger.info("上传：" + DateFormatUtils.HHmmss.format(new Date()));
            filePaths.append(",").append(filePath);
            fileNames.append(",").append(fileName);
        } else {
            try {
                SmbFile smbFile = new SmbFile(smbFileUrl, auth);
                String isNullable = (String) excDataFileMap.get(Contents.FILE_IS_NULL_ABLE);
                if (!smbFile.exists()) {
                    if (!Contents.boolean_true.equals(isNullable)) {
                        throw new BusinessException("路径：[" + smbFileUrl + "]数据不全,如可以为空请配置[FILE_IS_NULL_ABLE]的属性");
                    }
                } else {
                    SmbFileUtils.copyLocalFileFromRemote(f, smbFileUrl, auth);
                    String filePath = fileOperateService.uploadFile(f);
                    filePaths.append(",").append(filePath);
                    fileNames.append(",").append(fileName);
                    f.deleteOnExit();
                }
            } catch (Exception ex) {
                BusinessException.throwBusinessException(ex);
            }
        }
    }


}
